/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.news;

import java.util.ArrayList;
import java.util.List;
import com.example.android.news.RssParser.Item;

import android.app.Activity;
import android.support.v4.app.ListFragment;
import android.content.Context;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;

public class DetailsFragment extends ListFragment {
    private static final String TAG = DetailsFragment.class.getCanonicalName();
    private EfficientAdapter listAdapter;
    private LayoutInflater mInflater;
    NewsItemClickListener onClickListener;
    static List<Item> dataList = new ArrayList<Item>();
    ListView lv = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(TAG,"entered onActivityCreated");
        try {
            super.onActivityCreated(savedInstanceState);
        }catch(Exception e) {
            Log.e(TAG, e.toString(),e);
        }
        mInflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        listAdapter = new EfficientAdapter(getActivity(), R.layout.details_list_item, R.id.header, dataList);
        listAdapter.setInflater(mInflater);
        listAdapter.setDetailsFragment(this);
        setListAdapter(listAdapter);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
    }
    
    @Override
    public void onStart() {
        super.onStart();
        
        Log.d(TAG, "onStart");
        try {
            lv = getListView();
        }catch(IllegalStateException e) {
            Log.i(TAG,"Exception:" +  e.toString());
        }
        if(lv!= null) {
            try {
                onClickListener = new NewsItemClickListener();
                lv.setOnItemClickListener(onClickListener); 
            }catch(Exception e) {
                Log.e(TAG, e.toString(),e);
            }
            Log.d(TAG,lv.toString());
        }   
    }

    class NewsItemClickListener implements OnItemClickListener{
        String url = null;
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Item item = (Item)DetailsFragment.this.dataList.get((int)arg2);
            url = item.link;
            ((MainActivity)DetailsFragment.this.getActivity()).loadWebViewFragment(url);
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
    }
    
    public void setDataList(List<Item> list) {
        Log.i(TAG, "setDataList" );

        Log.d(TAG,"listAdapter:" + listAdapter);
        if(listAdapter != null) {
            listAdapter.clear();
            listAdapter.addAll(list);
            listAdapter.notifyDataSetChanged();
            try {
                lv.invalidate();
            }catch(IllegalStateException e) {
                Log.i(TAG,"Exception:" +  e.toString());
            }
        }
        this.dataList = list;
    }

    public static class EfficientAdapter extends ArrayAdapter<Item> {

        private DetailsFragment detailsFragment;
        private LayoutInflater inflator = null;

        @SuppressWarnings("unchecked")
        public EfficientAdapter(Context context, int resource,
                int textViewResourceId, List<Item> objects) {
            super(context, resource, textViewResourceId, objects);
        }
        
        public void setDetailsFragment(DetailsFragment fragment) {
            detailsFragment = fragment;
        }

        public void setInflater(LayoutInflater mInflater) {
            this.inflator = mInflater;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            try {
                if (convertView == null) {
                    convertView = this.inflator.inflate(R.layout.details_list_item, null);
                }
                Item item = (Item) getItem(position);

                holder = new ViewHolder();
                holder.header = (TextView) convertView.findViewById(R.id.header);
                holder.desc = (TextView) convertView.findViewById(R.id.desc);
                String header = item.title;
                String desc = item.description;
                if(desc != null) {
                    int indexOfLt = desc.indexOf("<");
                    String descTrim = "";
                    if(indexOfLt >= 0) {
                        descTrim = desc.substring(0, desc.indexOf("<"));
                    }else {
                        descTrim = desc;
                    }
                    holder.desc.setText(descTrim);
                }
                CharSequence sequence = header;
                holder.header.setText(sequence);
                
                convertView.setTag(holder);
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
            }
            return convertView;
        }

        static class ViewHolder {
            TextView header;
            TextView desc;
        }

        public Filter getFilter() {
            return null;
        }

        public long getItemId(int position) {
            return 1;
        }

        public int getCount() {
            return dataList.size();
        }

        public Item getItem(int position) {
            return (Item) super.getItem(position);
        }

        @Override
        public int getItemViewType(int position) {
            return super.getItemViewType(position);
        }

        @Override
        public int getViewTypeCount() {
            return super.getViewTypeCount();
        }

        @Override
        public boolean isEmpty() {
            return super.isEmpty();
        }
    }

    public void onClick(View arg0) {
        
    }
}

	
